package alipay.openplatform.edu.campus.jiuye.alipay.api.services;

import alipay.openplatform.edu.campus.jiuye.alipay.api.config.AlipayApiConfig;
import alipay.openplatform.edu.campus.jiuye.alipay.api.domain.StudentInfoQueryDomain;
import alipay.openplatform.edu.campus.jiuye.alipay.api.iservice.IAlipayApiService;
import alipay.openplatform.edu.campus.jiuye.alipay.api.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.EduStudentInfoShareResult;
import com.alipay.api.domain.StudentInfo;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.*;
import com.alipay.api.response.AlipayCommerceEducateStudentinfoShareResponse;
import com.alipay.api.response.AlipaySocialBaseMcommentStudentQueryResponse;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;
import com.alipay.api.response.AlipayUserUserinfoShareResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by suzunshou on 16/9/16.
 */
@Service
public class AlipayApiServiceImpl implements IAlipayApiService {

    private final static Logger logger = LoggerFactory.getLogger(AlipayApiServiceImpl.class);

    @Autowired
    private AlipayApiConfig alipayApiConfig;

    /**
     * 获取授权信息 access_token
     *
     * @param authCode 授权码
     * @return 返回null则获取失败
     */
    public String getAccessTokenByAuthCode(String authCode) {
        logger.info("authCode的值={}", authCode);
        AlipaySystemOauthTokenResponse response = getUserAuthResponse(authCode);
        if (response == null) {
            logger.error("获取用户授权结果失败");
            return null;
        } else {
            return response.getAccessToken();
        }
    }

    /**
     * 获取用户授权结果
     *
     * @param authCode
     * @return 返回null则授权失败
     */
    public AlipaySystemOauthTokenResponse getUserAuthResponse(String authCode) {
        AlipaySystemOauthTokenRequest request
                = new AlipaySystemOauthTokenRequest();
        request.setCode(authCode);
        request.setGrantType(alipayApiConfig.getGrant_type());
        try {
            AlipaySystemOauthTokenResponse response =
                    alipayApiConfig.getAlipayClient_info().execute(request);
            if (StringUtils.isNotBlank(response.getCode())) {
                logger.warn("获取用户授权结果失败", response.getSubMsg(), response.getSubMsg());
                return null;
            }
            return response;
        } catch (AlipayApiException e) {
            logger.error("获取用户授权结果失败,错误信息={}", e.getMessage());
            return null;
        }
    }

    /**
     * 获取用户信息
     *
     * @param access_token
     * @return 返回null则获取用户信息失败
     */
    public AlipayUserUserinfoShareResponse getUserInfoByAccessToken(String access_token) {
        AlipayUserUserinfoShareRequest request
                = new AlipayUserUserinfoShareRequest();
        try {
            AlipayUserUserinfoShareResponse response
                    = alipayApiConfig.getAlipayClient_info().execute(request, access_token);

            if (StringUtils.isNotBlank(response.getCode())) {
                logger.warn(response.getBody());
                return null;
            }
            return response;
        } catch (AlipayApiException e) {
            logger.error("UN_GET_USERINFO", "未能从支付宝获得用户信息!");
            return null;
        }
    }

    /**
     * 获取学历信息
     *
     * @param access_token
     * @return 返回null则获取学生信息失败
     */
    public StudentInfo getUserEducateInfoByAccessToken(String access_token) {
        AlipayCommerceEducateStudentinfoShareRequest request
                = new AlipayCommerceEducateStudentinfoShareRequest();
        AlipayCommerceEducateStudentinfoShareResponse response = null;
        try {
            response = alipayApiConfig.getAlipayClient_info().execute(request, access_token);
            if (!response.getCode().equals("10000")) {
                logger.error(response.getSubCode(), response.getSubMsg());
                return null;
            }
        } catch (AlipayApiException e) {
            logger.error("获取学历失败,错误信息={}", e);
            return null;
        }

        Map<String, Object> bodyMap = JSON.parseObject(response.getBody(), HashMap.class);
        String responsResult =
                JSON.toJSONString(
                        bodyMap.get("alipay_commerce_educate_studentinfo_share_response"));
        EduStudentInfoShareResult result = JSON.parseObject(responsResult, EduStudentInfoShareResult.class);
        List<StudentInfo> studentInfos = result.getStudentInfos();
        return studentInfos.size() > 0 ? studentInfos.get(0) : null;
    }

    /**
     * 获取新生老生学历二合一接口
     *
     * @param accessToken
     * @return
     */
    public StudentInfoQueryDomain queryStudentInfoByAccessToken(String accessToken) {
        AlipaySocialBaseMcommentStudentQueryRequest
                request = new AlipaySocialBaseMcommentStudentQueryRequest();

        try {
            AlipaySocialBaseMcommentStudentQueryResponse response
                    = alipayApiConfig.getAlipayClient_info().execute(request, accessToken);
            if (!response.isSuccess() || !response.getCode().equals("10000")) {
                logger.error("获取学历失败,错误信息={}", response.getSubMsg());
                return null;
            } else {
                StudentInfoQueryDomain StudentInfoDomain = new StudentInfoQueryDomain();
                StudentInfoDomain.setUserId(response.getUserId());
                StudentInfoDomain.setCampusName(response.getCampusName());
                StudentInfoDomain.setCampusCode(response.getCampusCode());
                StudentInfoDomain.setDegree(response.getDegree());
                StudentInfoDomain.setProvinceCode(response.getProvinceCode());
                StudentInfoDomain.setProvinceName(response.getProvinceName());
                StudentInfoDomain.setEnrollmentTime(response.getEnrollmentTime());
                StudentInfoDomain.setGraduationTime(response.getGraduationTime());
                StudentInfoDomain.setStatusEnum(response.getStatusEnum());
                return StudentInfoDomain;
            }

        } catch (AlipayApiException e) {
            logger.error("获取新生或老生信息失败,e={}", e);
            return null;
        }
    }

    /**
     * 唤醒支付宝收银台,返回收银台表单
     *
     * @param out_trade_no 商户订单号
     * @param total_amount 总金额
     * @param subject      订单标题
     * @return
     * @throws AlipayApiException
     * @throws IOException
     */
    public String invokeCheckOutPage(String out_trade_no, String total_amount, String subject) throws AlipayApiException, IOException {
        Map<String, String> map = new HashMap();
        map.put("out_trade_no", out_trade_no);
        map.put("total_amount", total_amount);
        map.put("subject", subject);
        map.put("seller_id", alipayApiConfig.getSeller_id());
        map.put("product_code", alipayApiConfig.getProduct_code());
        logger.info("传递给支付宝的信息为:map={}", map);

        AlipayTradeWapPayRequest alipayTradeWapPayRequest = new AlipayTradeWapPayRequest();
        alipayTradeWapPayRequest.setNotifyUrl(alipayApiConfig.getNotifyUrl());
        alipayTradeWapPayRequest.setReturnUrl(alipayApiConfig.getReturnUrl());
        alipayTradeWapPayRequest.setBizContent(JSON.toJSONString(map));
        return alipayApiConfig.getAlipayClient_pay().pageExecute(alipayTradeWapPayRequest).getBody();
    }

    /**
     * 验签
     *
     * @param params 待签名参数,
     *               可通过自定义的AlipayUtils#getParamsFromGetRequestParams(java.util.Map)获取
     * @return
     */
    public boolean verify(Map<String, String> params) throws AlipayApiException {
        return AlipaySignature.rsaCheckV1(params, alipayApiConfig.getPublicKey(), alipayApiConfig.getCharset());
    }
}

